#ifndef __RTC_WORKER_H_
#define __RTC_WORKER_H_
#include "server/rtc_server.h"
#include "base/event_loop.h"
#include <thread>
#include "xrtcserver_def.h"
#include "base/lock_free_queue.h"
#include "stream/rtc_stream_manager.h"

namespace xrtc
{
    class RtcWorker
    {
        enum
        {
            QUIT = 0,
            RTC_MSG = 1
        };

    public:
        RtcWorker(int worker_id, const RtcServerOptions &options);
        ~RtcWorker();
        int Init();
        bool Start();
        void Stop();
        void Join();
        int Notify(int msg);

        int SendRtcMsg(std::shared_ptr<RtcMsg> msg);
        void PushMsg(std::shared_ptr<RtcMsg> msg);
        bool PopMsg(std::shared_ptr<RtcMsg> *msg);
        int worker_id() { return worker_id_; }
        RtcStreamManager *rtc_stream_mgr() { return rtc_stream_mgr_.get(); }

        friend void RtcWorkerRecvNotify(EventLoop *, IOWatcher *, int fd, int /*events*/, void *data);

    private:
        void ProcessNotify(int msg);
        void Stop_(); //_stop
        void ProcessRtcMsg();
        void ProcessAnswer(std::shared_ptr<RtcMsg> msg);
        void ProcessPush(std::shared_ptr<RtcMsg> msg);
        void ProcessStopPush(std::shared_ptr<RtcMsg> msg);
        void ProcessPull(std::shared_ptr<RtcMsg> msg);
        void ProcessStopPull(std::shared_ptr<RtcMsg> msg);

    private:
        RtcServerOptions options_;
        int worker_id_;
        EventLoop *el_ = nullptr;
        IOWatcher *pipe_watcher_ = nullptr;
        int notify_recv_fd_ = -1;
        int notify_send_fd_ = -1;
        std::thread *thread_ = nullptr;
        LockFreeQueue<std::shared_ptr<RtcMsg>> q_msg_;
        std::unique_ptr<RtcStreamManager> rtc_stream_mgr_;
    };

} // namespace xrtc

#endif